<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               v-model:search="search"
               v-model:page="page"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @on-load="onLoad">
      <template #menu-left>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.task_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>

      <template #areaIds="{row}">
        <el-tag v-if="row.areaName">{{row.areaName}}</el-tag>
      </template>
      <template #userIds="{row}">
        <el-tag v-if="row.realName">{{row.realName}}</el-tag>
      </template>
      <template #status="{row}">
        <el-switch v-model="row.status" :active-value="1" :inactive-value="0" disabled></el-switch>
      </template>
    </avue-crud>

    <el-dialog :title="`任务下发`"
               v-model="drawerVisibleIssue"
               :direction="direction"
               append-to-body
               size="50%">
      <basic-container>
        <avue-form :option="optionIssue" v-model="formIssue"  @submit="handleIssueSubmit"></avue-form>
      </basic-container>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove,taskIssue} from "@/api/restaurant/task";
  import {getAreaTree} from "@/api/restaurant/area";
  import {mapGetters} from "vuex";
  import {baseUrl} from "@/config/env";
  import func from "@/utils/func";
  import { getUserAttendance, userList } from '@/api/restaurant/common';

  export default {
    data() {
      return {
        drawerVisibleIssue: false,
        formIssue: {},
        direction: 'rtl',
        optionIssue: {
          emptyBtn: false,
          column: [
            {
              label: "负责用户",
              prop: "userIds",
              multiple: false,
              filterable: true,
              type: "tree",
              dicUrl: baseUrl + '/restaurant/common/userAttendance',
              dicData: [],
              props: {
                label: "realName",
                value: 'id'
              },
              slot: true,
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请输入负责用户",
                trigger: "click"
              }]
            },
            {
              label: "任务类型",
              prop: "timeType",
              type: "select",
              search: true,
              props: {
                label: 'dictValue',
                value: 'dictKey'
              },
              dicUrl: baseUrl + "/blade-system/dict/dictionary?code=task_time_type",
              rules: [{
                required: true,
                message: "请输入任务类型",
                trigger: "blur"
              }]
            },
            {
              label: "截止日期",
              prop: "deadline",
              type: 'datetime',
              format: 'YYYY-MM-DD HH:mm:ss',
              valueFormat: 'YYYY-MM-DD HH:mm:ss',
              rules: [{
                required: true,
                message: "请输入任务日期",
                trigger: "blur"
              }]
            },
          ]
        },
        form: {},
        query: {},
        search: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          height: 'auto',
          calcHeight: 210,
          searchShow: true,
          searchMenuSpan: 6,
          tip: false,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          column: [
            {
              label: "任务时间",
              prop: "taskTime",
              search: true,
              rules: [{
                required: true,
                message: "请输入任务时间",
                trigger: "blur"
              }]
            },

            {
              label: "下发人",
              prop: "userIds",
              multiple: false,
              filterable: true,
              type: "tree",
              dicData: [],
              props: {
                label: "realName",
                value: 'id'
              },
              slot: true,
              checkStrictly: true,
              rules: [{
                required: true,
                message: "请输入下发人",
                trigger: "click"
              }]
            },
            {
              label: "任务名",
              prop: "taskName",
              rules: [{
                required: true,
                message: "请输入任务名",
                trigger: "blur"
              }]
            },
            {
              label: '任务类型',
              prop: 'timeType',
              type: 'select',
              search: true,
              props: {
                label: 'dictValue',
                value: 'dictKey'
              },
              dicUrl: baseUrl + '/blade-system/dict/dictionary?code=task_time_type',
              rules: [{
                required: true,
                message: '请输入任务类型',
                trigger: 'blur'
              }]
            },
            {
              label: "任务周期",
              type: "select",
              dicUrl: baseUrl + "/blade-system/dict/dictionary?code=task_cycle",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              slot: true,
              prop: "cycle",
              search: true,
              rules: [{
                required: true,
                message: "请输入任务周期",
                trigger: "blur"
              }],
              visibleChange: () => {
                console.log('=====')
              }
            },
            {
              label: "分配区域",
              prop: "areaIds",
              multiple: false,
              filterable: true,
              type: "tree",
              dicData: [],
              props: {
                label: "title"
              },
              slot: true,
              checkStrictly: true,
              rules: [{
                required: false,
                message: "请分配区域",
                trigger: "click"
              }]
            },
            {
              label: "示例图",
              prop: "sampleGraph",
              type: "upload",
              overHidden: true,
              listType: "picture-card",
              action: "/api/blade-resource/oss/endpoint/put-file",
              propsHttp: {
                res: 'data',
                url: 'link'
              },
              span: 24,
              rules: [{
                required: true,
                message: "请输入示例图",
                trigger: "blur"
              }]
            },
            {
              label: "注意事项",
              prop: "announcements",
              overHidden: true,
              component: 'avue-ueditor',
              span: 24,
              minRows: 4,
              type: "textarea"
            },
            {
              label: '执行截止时间',
              prop: 'deadline',
              type: 'time',
              format: 'HH:mm',
              valueFormat: 'HH:mm',
              rules: [{
                required: true,
                message: '请输入执行截止时间',
                trigger: 'blur'
              }]
            },
            {
              label: '检查截止时间',
              prop: 'inspectDeadline',
              type: 'time',
              format: 'HH:mm',
              valueFormat: 'HH:mm',
              rules: [{
                required: true,
                message: '请输入检查截止时间',
                trigger: 'blur'
              }]
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.task_add, false),
          viewBtn: this.validData(this.permission.task_view, false),
          delBtn: this.validData(this.permission.task_delete, false),
          editBtn: this.validData(this.permission.task_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      handleIssue(row) {
        this.formIssue = row;
        this.drawerVisibleIssue = true;
      },
      handleIssueSubmit(row, done){
        taskIssue(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.drawerVisibleIssue = false;
        }, error => {
          window.console.log(error);
        })
      },
      rowSave(row, done, loading) {

        if (Array.isArray(row.areaIds)) {
          row.areaIds = func.join(row.areaIds);
        }
        if (Array.isArray(row.userIds)) {
          row.userIds = func.join(row.userIds);
        }
        if (Array.isArray(row.sampleGraph)) {
          row.sampleGraph = func.join(row.sampleGraph);
        }
        add(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowUpdate(row, index, done, loading) {

        if (Array.isArray(row.areaIds)) {
          row.areaIds =func.join(row.areaIds);
        }

        if (Array.isArray(row.userIds)) {
          row.userIds =func.join(row.userIds);
        }

        if (Array.isArray(row.sampleGraph)) {
          row.sampleGraph =func.join(row.sampleGraph);
        }
        update(row).then(() => {
          done();
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        }, error => {
          window.console.log(error);
          loading();
        });
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },

      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            if (this.form.hasOwnProperty("areaIds")) {
              this.form.areaIds = this.form.areaIds.split(",");
            }
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;

          getAreaTree().then(res => {
            const column = this.findObject(this.option.column, "areaIds");
            column.dicData = res.data.data;
          });
          getUserAttendance().then(res => {
            const column = this.findObject(this.option.column, "userIds");
            column.dicData = res.data.data;
          });

          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
